# views/main_window.py

import os
import json
import logging
from datetime import datetime
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QTabWidget, QApplication
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import QFileSystemWatcher
from utils.keyboard_shortcuts import KeyboardShortcuts
from utils.image_utils import ImageUtils
from views.viewer import Viewer
from views.gallery import Gallery
from views.favorites import Favorites
import resources_rc  # 导入资源文件

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("imageViewer 图像查看器 v1.4")
        self.setWindowIcon(QIcon(':/icon.ico'))  # 使用资源路径
        self.setGeometry(100, 100, 1200, 800)

        # 设置全局字体
        font = QFont()
        font.setPointSize(12)  # 增大字体大小
        self.setFont(font)

        # 初始化变量
        self.directory = ""
        self.favorites = set()
        self.auto_update = False
        self.settings_file = "settings.json"

        # 读取设置
        self.load_settings()

        # 检查过期日期
        expiration_date = datetime(2024, 10, 29)
        current_date = datetime.now()
        if current_date > expiration_date:
            QMessageBox.critical(self, "软件已过期", "该软件的测试版本已过期，请联系开发者。")
            logging.critical("软件已过期，应用程序即将退出。")
            QApplication.quit()

        # 初始化文件系统监视器
        self.watcher = QFileSystemWatcher()
        if self.directory and os.path.isdir(self.directory):
            self.watcher.addPath(self.directory)
            self.watcher.directoryChanged.connect(self.on_directory_changed)
            logging.info(f"已添加监视目录: {self.directory}")

        # 创建选项卡
        self.tab_widget = QTabWidget()
        self.setCentralWidget(self.tab_widget)

        # 创建各个视图
        self.viewer = Viewer(self)
        self.gallery = Gallery(self)
        self.favorites_view = Favorites(self)

        self.tab_widget.addTab(self.viewer, "图片查看")
        self.tab_widget.addTab(self.gallery, "图库")
        self.tab_widget.addTab(self.favorites_view, "收藏")

        # 设置接受拖放，仅在图片查看界面
        self.setAcceptDrops(False)
        self.viewer.setAcceptDrops(True)

        # 如果目录存在，则自动加载图片
        if self.directory and os.path.isdir(self.directory):
            self.viewer.load_images()
            self.gallery.load_images()
            self.favorites_view.load_favorites()
        else:
            self.viewer.display_placeholder()
            self.gallery.display_placeholder()
            self.favorites_view.display_placeholder()

        # 启动自动更新
        if self.auto_update:
            self.start_watching_directory()

    def load_settings(self):
        if not os.path.isfile(self.settings_file):
            # 创建默认设置文件
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump({"directory": "", "favorites": [], "auto_update": False}, f, ensure_ascii=False, indent=4)
            logging.info("默认设置文件已创建。")
            return

        try:
            with open(self.settings_file, 'r', encoding='utf-8') as f:
                settings = json.load(f)
                self.directory = settings.get("directory", "")
                self.favorites = set(settings.get("favorites", []))
                self.auto_update = settings.get("auto_update", False)
            logging.info("设置已加载。")
        except Exception as e:
            QMessageBox.warning(self, "警告", f"加载设置失败：{e}")
            logging.error(f"加载设置失败：{e}")

    def save_settings(self):
        settings = {
            "directory": self.directory,
            "favorites": list(self.favorites),
            "auto_update": self.auto_update
        }
        try:
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=4)
            logging.info("设置已保存。")
        except Exception as e:
            QMessageBox.warning(self, "警告", f"保存设置失败：{e}")
            logging.error(f"保存设置失败：{e}")

    def closeEvent(self, event):
        self.save_settings()
        self.stop_watching_directory()
        # 确保图像处理工具关闭
        self.viewer.image_utils.shutdown()
        self.gallery.image_utils.shutdown()
        self.favorites_view.image_utils.shutdown()
        event.accept()
        logging.info("应用程序已关闭。")

    def start_watching_directory(self):
        if self.directory and os.path.isdir(self.directory):
            if self.directory not in self.watcher.directories():
                self.watcher.addPath(self.directory)
                logging.info(f"开始监视目录: {self.directory}")
        else:
            logging.warning("无法启动目录监视：目录不存在。")

    def stop_watching_directory(self):
        if self.directory and self.directory in self.watcher.directories():
            self.watcher.removePath(self.directory)
            logging.info(f"停止监视目录: {self.directory}")

    def on_directory_changed(self, path):
        logging.info(f"目录变化检测到: {path}")
        self.viewer.load_images()
        self.gallery.load_images()
        self.favorites_view.load_favorites()

    # 拖放事件处理，委托给 Viewer
    def dragEnterEvent(self, event):
        if self.viewer.isVisible() and event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event):
        if self.viewer.isVisible():
            self.viewer.dropEvent(event)
